package bishi.xunfei;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/08/15 19:55
 */

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

public class three {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.left.left = new TreeNode(6);
        root.left.right.right = new TreeNode(7);
        System.out.println(leafPairs(root, 3));
    }

    static int res = 0;
    public static int leafPairs(TreeNode root, int k) {
        dfs(root,k);
        return res;
    }

    public static List<Integer> dfs(TreeNode root, int k) {
        if (root.left == null && root.right == null) {
            return new ArrayList<Integer>() {{
                add(0);
            }};
        }
        ArrayList<Integer> list = new ArrayList<>();
        if (root.right != null) {
            List<Integer> dfs = dfs(root.right, k);
            for (Integer df : dfs) {
                if (df == k - 1) res++;
                else list.add(df + 1);
            }
            if (root.left != null) {
                dfs = dfs(root.left, k);
                int len = list.size();
                for (Integer df : dfs) {
                    if (df < k) {
                        list.add(df + 1);
                    }
                    for (int i = 0; i < len; i++) {
                        if (list.get(i) + df + 1 == k) res++;
                    }
                }
            }
        } else {
            List<Integer> dfs = dfs(root.left, k);
            for (Integer df : dfs) {
                if (df < k) {
                    list.add(df + 1);
                }
            }
        }
        return list;
    }
}
